package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderConfigMapper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private OrderConfigMapper orderConfigMapper;
    @Autowired
    private CartService cartService;
    @Reference
    private SkuService skuService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增订单
     *
     * @param order
     */
    @Transactional
    public Map<String, Object> add(Order order) {
        List<Map<String, Object>> orderItemList=null;
        try {
            orderItemList = cartService.findOrderItem(order.getUsername());
            //获取选中购物车
            List<OrderItem> orderItems = orderItemList.stream().filter(cart -> (boolean) cart.get("checked"))
                    .map(cart -> (OrderItem) cart.get("item"))
                    .collect(Collectors.toList());
            boolean isStore = skuService.decrStore(orderItems);
            if (!isStore) {
                throw new RuntimeException("库存数量不足");
            }
            //可以扣减库存
            order.setId(idWorker.nextId() + "");
            int totalNum = orderItems.stream().mapToInt(OrderItem::getNum).sum();
            int totalMoney = orderItems.stream().mapToInt(OrderItem::getMoney).sum();
            int preMoney = cartService.preferential(order.getUsername());
            order.setTotalNum(totalNum);//总数量
            order.setTotalMoney(totalMoney);//总金额
            order.setPreMoney(preMoney);//优惠金额
            order.setPayMoney(totalMoney - preMoney);//实付金额
            order.setCloseTime(new Date());
            order.setOrderStatus("0");
            order.setPayStatus("0");
            order.setConsignStatus("0");
            //新增订单项
            orderMapper.insert(order);
            //计算折扣
            double disCount = order.getPayMoney() / totalMoney;
            //遍历订单详细
            for (OrderItem orderItem : orderItems) {
                orderItem.setOrderId(order.getId());
                orderItem.setId(idWorker.nextId() + "");
                //输入实付金额
                orderItem.setPayMoney((int) (orderItem.getMoney() * disCount));
                //添加订单明细
                orderItemMapper.insert(orderItem);
            }
            //清理购物车
            cartService.deleteCheckedCart(order.getUsername());
            //还回订单编号和支付金额
            Map map = new HashMap();
            map.put("orderSn", order.getId());
            map.put("money", order.getPayMoney());
            return map;
        } catch (RuntimeException e) {
            rabbitTemplate.convertAndSend("","queue.skuback" ,JSON.toJSONString(orderItemList));
           throw new RuntimeException("创建订单失败",e);
        }
    }

    /**
     * 修改
     *
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public OrderAndItems findOrderAndItemsById(String id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", id);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
        return new OrderAndItems(order, orderItemList);
    }

    public List<Order> findconSignList(Map<String, Object> map) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (map.get("ids") != null) {
            List<String> ids = JSON.parseArray(map.get("ids").toString(), String.class);
            criteria.andIn("id", ids);
        }
        criteria.andEqualTo("consignStatus", (String) map.get("consignStatus"));
        List<Order> orderList = orderMapper.selectByExample(example);
        return orderList;
    }

    @Transactional
    public void batchSend(List<Order> orders) {
        for (Order order : orders) {
            if (order.getShippingCode() == null || order.getShippingName() == null) {
                throw new RuntimeException("物流公司名或者物流单号为空");
            }
            order.setOrderStatus("3");
            order.setConsignStatus("2");
            order.setConsignTime(new Date());
            orderMapper.updateByPrimaryKey(order);

            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("system");
            orderLog.setConsignStatus("2");
            orderLog.setOrderId(Long.parseLong(order.getId()));
            orderLog.setOperateTime(new Date());
            orderLog.setOrderStatus(order.getOrderStatus());
            orderLog.setPayStatus(order.getPayStatus());
            orderLogMapper.insert(orderLog);
        }
    }

    @SuppressWarnings("unchecked")
    public void orderTimeOutLogic() {
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        Integer orderTimeout = orderConfig.getOrderTimeout();
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(orderTimeout);
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime", localDateTime);
        criteria.andEqualTo("orderStatus", "0");
        criteria.andEqualTo("isDelete", "0");
        List<Order> orders = orderMapper.selectByExample(example);
        Date date = new Date();
        for (Order order : orders) {
            order.setOrderStatus("4");
            order.setCloseTime(date);
            orderMapper.updateByPrimaryKeySelective(order);

            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOrderId(Long.parseLong(order.getId()));
            orderLog.setOperateTime(date);
            orderLog.setOperater("system");
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("超时订单，系统自动关闭");
            orderLogMapper.insert(orderLog);
        }

    }

    @Transactional
    public void merge(String toId, String fromId) {
        //查询主从订单
        Order majorOrder = orderMapper.selectByPrimaryKey(toId);
        Order minorOrder = orderMapper.selectByPrimaryKey(fromId);
        //总数量
        majorOrder.setTotalNum((majorOrder.getTotalNum() == null ? 0 : majorOrder.getTotalNum()) + (minorOrder.getTotalNum() == null ? 0 : minorOrder.getTotalNum()));
        //总金额
        majorOrder.setTotalMoney((majorOrder.getTotalMoney() == null ? 0 : majorOrder.getTotalMoney()) + (minorOrder.getTotalMoney() == null ? 0 : minorOrder.getTotalMoney()));
        //总优惠金额
        majorOrder.setPreMoney((majorOrder.getPreMoney() == null ? 0 : majorOrder.getPreMoney()) + (minorOrder.getPreMoney() == null ? 0 : minorOrder.getPreMoney()));
        //总邮费
        majorOrder.setPostFee((majorOrder.getPostFee() == null ? 0 : majorOrder.getPostFee()) + (minorOrder.getPostFee() == null ? 0 : minorOrder.getPostFee()));
        //设置支付费用
        majorOrder.setPayMoney((majorOrder.getPayMoney() == null ? 0 : majorOrder.getPayMoney()) + (minorOrder.getPayMoney() == null ? 0 : minorOrder.getPayMoney()));
        //设置更新时间
        majorOrder.setUpdateTime(new Date());
        //更新订单明细表
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", fromId);
        List<OrderItem> minorOrderItems = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : minorOrderItems) {
            orderItem.setOrderId(toId);
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }
        //更新主订单
        orderMapper.updateByPrimaryKeySelective(majorOrder);
        //更新从订单
        minorOrder.setIsDelete("1");
        orderMapper.updateByPrimaryKeySelective(minorOrder);
        //设置订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOrderId(Long.parseLong(toId));
        orderLog.setConsignStatus(majorOrder.getConsignStatus());
        orderLog.setPayStatus(majorOrder.getPayStatus());
        orderLog.setOperater("system");
        orderLog.setOperateTime(new Date());
        orderLog.setOrderStatus(majorOrder.getOrderStatus());
        orderLog.setRemarks("合并订单" + toId + "和" + fromId);
        orderLogMapper.insert(orderLog);

    }

    @Override
    public void updatePayStatus(String orderId, String trsactionId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order!=null&&"0".equals(order.getPayStatus())){//订单存在且未支付
            order.setPayStatus("1");
            order.setOrderStatus("1");
            order.setUpdateTime(new Date());
            order.setPayTime(new Date());
            order.setTransactionId(trsactionId);
            orderMapper.updateByPrimaryKeySelective(order);
            //记录日志
            OrderLog log=new OrderLog();
            log.setOperater("system");
            log.setOperateTime(new Date());
            log.setOrderStatus("1");
            log.setPayStatus("1");
            log.setRemarks("支付流水号："+trsactionId);
            log.setOrderId(Long.parseLong(orderId));
            orderLogMapper.insert(log);

        }
    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andLike("payType", "%" + searchMap.get("payType") + "%");
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andLike("sourceType", "%" + searchMap.get("sourceType") + "%");
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andLike("orderStatus", "%" + searchMap.get("orderStatus") + "%");
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andLike("payStatus", "%" + searchMap.get("payStatus") + "%");
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andLike("consignStatus", "%" + searchMap.get("consignStatus") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
